<?php
/**
 * My new Zend Framework project
 * 
 * @author  
 * @version 
 */
/**
 * 
 * Initializes configuration depndeing on the type of environment 
 * (test, development, production, etc.)
 *  
 * This can be used to configure environment variables, databases, 
 * layouts, routers, helpers and more
 *   
 */
class My_Plugin_Initializer extends Zend_Controller_Plugin_Abstract
{
    /**
     * @var Zend_Config
     */
    protected static $_config;
    /**
     * @var string Current environment
     */
    protected $_env;
    /**
     * @var Zend_Controller_Front
     */
    protected $_front;
    /**
     * @var Bootstrap
     */
    protected $_bootstrap;
    /**
     * @var string Path to application root
     */
    protected $_root;
    /**
     *@var Zend_View
     */
    protected $_view;
    /**
     * Constructor
     *
     * Initialize environment, root path, and configuration.
     * 
     * @param  string $env 
     * @param  string|null $root 
     * @return void
     */
    public function __construct ($env, $root = null)
    {
        $this->_setEnv($env);
        if (null === $root) {
            $root = realpath(dirname(__FILE__) . '/../');
        }
        $this->_root = $root;
        $this->_front = Zend_Controller_Front::getInstance();
        $this->_front->registerPlugin(new Zend_Controller_Plugin_ErrorHandler());
    }

    /**
     * Route startup
     * 
     * @return void
     */
    public function routeStartup (Zend_Controller_Request_Abstract $request)
    {
        $this->_initConfig();
        $this->_initAutoLoader();
        $this->_initModuleAutoloader();
        $this->_initResourceAutoloader();
        var_dump($this->_initDb());
        $this->_initSession();
        $this->_initView();
        $this->_initDoctype();
        $this->_initHelpers();
        $this->_initPlugins();    
        $this->_initLayoutHelper();
    }

    protected function _initConfig ()
    {
        $this->_bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $config = new Zend_Config($this->_bootstrap->getOptions());
        
        Zend_Registry::set('config', $config);
        return $config;
               
    }
   
    /**
     * Initialize environment
     * 
     * @param  string $env 
     * @return void
     */
    protected function _setEnv ($env)
    {
        $this->_env = $env;
    }
    protected function _initView ()
    {
        // Initialize view
        $view = new Zend_View();
        // Add it to the ViewRenderer
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
        $viewRenderer->setView($view);
        // Return it, so that it can be stored by the bootstrap
        return $view;
    }
    /**
     * Initialize  Autoloader
     * This will store autoloader to bootstrap.
     * 
     * @return 
     */
    protected function _initAutoLoader ()
    {
        $autoLoader = Zend_Loader_Autoloader::getInstance();
        $autoLoader->registerNamespace('My_');
        // Return it so that it can be stored by the bootstrap
        return $autoLoader;
    }
    /**
     * Initialize Module Autoloader
     * This will autoload to models, filters, helpers, etc... for our default module.
     * 
     * @return 
     */
    protected function _initModuleAutoloader ()
    {
        $moduleAutoLoader = new Zend_Application_Module_Autoloader(array('namespace' => 'Default_' , 'basePath' => dirname(__FILE__)));
        // Return it so that it can be stored by the bootstrap
        return $moduleAutoLoader;
    }
    /**
     * Initialize Resource Autoloader
     * This will autoload to models, filters, helpers, etc... for our default module.
     * 
     * @return 
     */
    protected function _initResourceAutoloader ()
    {
        $resourceLoader = new Zend_Loader_Autoloader_Resource(array('basePath' => APPLICATION_PATH , 'namespace' => '' , 'resourceTypes' => array('form' => array('path' => 'forms/' , 'namespace' => 'Form_') , 'model' => array('path' => 'models/' , 'namespace' => 'Model_'))));
        // Return it so that it can be stored by the bootstrap
        return $resourceLoader;
    }
    /**
     * Initialize data bases
     * 
     * @return void
     */
    protected function _initDb ()
    {
        $this->_bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $resource = $this->_bootstrap->getPluginResource('db');
        $db = $resource->getDbAdapter();
        Zend_Registry::set("db", $db);
        return $db;
    }
    protected function _initLayoutHelper ()
    {
        $this->_bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $layout = Zend_Controller_Action_HelperBroker::addHelper(new My_Controller_Action_Helper_LayoutLoader());
    }
    protected function _initDoctype ()
    {
        $this->_bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $view = $this->_bootstrap->getResource('view');
        $view->doctype('XHTML1_STRICT');
    }
    /**
     * Initialize action helpers
     * 
     * @return void
     */
    protected function _initHelpers ()
    {
        //register My Controller Action Helpers
        Zend_Controller_Action_HelperBroker::addPath(APPLICATION_PATH . '/../library/My/Controller/Action/Helper', 'My_Controller_Action_Helper');
    }
    /**
     * Initialize plugins 
     * 
     * @return void
     */
    protected function _initPlugins ()
    {
        $this->_front->registerPlugin(new My_Plugin_ViewSetup());
        /*
         * Controller Plugin 
         * Plugins allow user code to be called when certain events occurs in the controller process life time.
         * TODO: remove in production
         */
        $this->_front->registerPlugin(new My_Controller_Plugin_Simple());
        /*Note that we want the ActionSetup's postDispatch() hook to run after all other plugins 
	     *except Zend_Layout, so we set the position of the plug-in to 98.
	     *We choose 98 because 99 is already used by Zend_Layout and we want ViewSetup to 
	     *to run just before Zend_Layout renders the action's view.
	     * LIFO - Last In, First Out action stack
	     */
        $this->_front->registerPlugin(new My_Plugin_ActionSetup(), 98);
    }
    protected function _initCachePlugin ()
    {
        //set up global cache
        // cache lifetime of 2 hours
        $frontend = 'Output';
        $backend = 'File';
        $frontendOptions = array('lifetime' => 7200 , 'automatic_serialization' => true);
        // Directory where to put the cache files
        $backendOptions = array('cache_dir' => APPLICATION_PATH . '/data/cache');
        $this->_front->registerPlugin(new My_Plugin_CacheSetup($options = array('frontend' => $frontend , 'backend' => $backend , 'frontendOptions' => $frontendOptions , 'backendOptions' => $backendOptions)));
    }
    protected function _initSession ()
    {
        $config = array('name' => 'sessions' , 'primary' => 'session_id' , 'modifiedColumn' => 'modified' , 'dataColumn' => 'data' , 'lifetimeColumn' => 'lifetime');
        Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_DbTable($config));
        Zend_Session::start();
    }
}